import { _decorator, AudioClip, AudioSource, Component, Node } from 'cc';
import { ResourceLoad, ServiceLocator } from '../service';
import { STATE } from 'db://assets/enum';
import { Chapter } from 'db://assets/store';
const { ccclass, property } = _decorator;

@ccclass('AudioManager')
export class AudioManager extends Component {
    #services = ServiceLocator;
    #resourceLoad = new ResourceLoad()

    get audioSource() {
        return this.getComponent(AudioSource)
    }

    volume = 0;

    protected onLoad(): void {

    }

    async playBGM(content: LDContent.BGMContent) {
        const chapter = this.#services.get<Chapter>(STATE.CHAPTER)
        const bgm = chapter.getResource(content.resourceId)
        const clip = await this.#resourceLoad.loadRemote<AudioClip>(bgm.ossUrl)
        if (content.repeat) {
            this.playRepeat(clip)
        } else {
            this.playOnce(clip)
        }
    }

    async playAudio(content: LDContent.AudioContent) {
        const chapter = this.#services.get<Chapter>(STATE.CHAPTER)
        const audio = chapter.getResource(content.resourceId)
        const clip = await this.#resourceLoad.loadRemote<AudioClip>(audio.ossUrl)
        this.playOnce(clip, content.volume)
    }

    playOnce(clip: AudioClip, volume = 1) {
        this.audioSource.clip = clip;
        this.audioSource.playOneShot(clip, this.volume * volume);
    }

    playRepeat(clip: AudioClip, volume = 1) {
        this.audioSource.clip = clip;
        this.audioSource.loop = true;
        this.audioSource.volume = this.volume * volume;
        this.audioSource.play();
    }
}

